var CT = require('./modules/country-list');
var AM = require('./modules/account-manager');
var EM = require('./modules/email-dispatcher');
var EXM = require('./modules/excel-manager');
var IFM = require('./modules/information-manager');
var FIM = require('./modules/file-manager');
var REM = require('./modules/reservation-manager'); //管理预约
var WRM = require('./modules/weather-manager'); //管理天气


//哈希函数
var crypto = require('crypto');
var moment = require('moment');

module.exports = function (app) {

    // main login page //
    app.get('/', function (req, res) {
        if (req.cookies.user == undefined || req.cookies.pass == undefined) {
            res.render('login', {title: '请登录'});
        } else {
            AM.autoLogin(req.cookies.user, req.cookies.pass, function (o) {
                if (o != null) {
                    req.session.user = o;
                    res.redirect('/home');
                } else {
                    res.render('login', {title: '请登录'});
                    // res.render('login', {title: 'Hello - Please Login To Your Account'});
                }
            });
        }
    });

    app.post('/', function (req, res) {
        AM.manualLogin(req.body['user'], req.body['pass'], function (result) {
            // e, o
            if (result.id == 1) {
                req.session.user = result.data;
                if (req.body['remember-me'] == 'true') {
                    res.cookie('user', result.data.user, {maxAge: 900000});
                    res.cookie('pass', result.data.pass, {maxAge: 900000});
                }
            }
            result['data'] = null;
            res.status(200).send(result);
        });
    });

    // creating new accounts //
    app.get('/signup', function (req, res) {
        res.render('signup', {title: '注册申请'});
    });

    app.post('/signup', function (req, res) {
        console.log(' --- post singup --- ');
        console.log(' --- user ---' + req.body['user']);
        //图片base64
        AM.addNewAccount({
            'user': req.body['user'],
            'pass': req.body['pass'],
            'inc-name': req.body['inc-name'],
            'inc-address': req.body['inc-address'],
            'inc-property': req.body['inc-property'],
            'contact-name': req.body['contact-name'],
            'contact-phone': req.body['contact-phone'],
            'contact-email': req.body['contact-email'],
            'contact-tel': req.body['contact-tel'],
            'contact-position': req.body['contact-position'],
            'inc-number': req.body['inc-number'],
            'inc-industry': req.body['inc-industry'],
            'business-license': req.body['business-license'],
            'organization-code': req.body['organization-code']
        }, function (result) {
            console.log(' result ---- ' + result);
            res.status(200).send(result);
        });
    });

    // password reset //
    app.post('/lost-password', function (req, res) {
        // look up the user's account via their email //
        AM.getAccountByEmail(req.body['email'], function (o) {
            if (o) {
                EM.dispatchResetPasswordLink(o, function (e, m) {
                    // this callback takes a moment to return //
                    // TODO add an ajax loader to give user feedback //
                    if (!e) {
                        res.status(200).send('ok');
                    } else {
                        for (k in e) console.log('ERROR : ', k, e[k]);
                        res.status(400).send('unable to dispatch password reset');
                    }
                });
                0
            } else {
                res.status(400).send('email-not-found');
            }
        });
    });

    // 提示用户信息
    app.post('/user-msg', function (req, res) {
        // look up the user's account via their email //
        //获取用户邮箱
        var userId = String(req.body['user_id']);
        var msg = String(req.body['msg']);
        var status = Number(req.body['status']);

        var subject;
        if (status == 2) {
            subject = '同意申请'
        } else {
            subject = '拒绝申请'
        }
        console.log(' --- id ---： ' + userId);
        AM.getRecords(userId, function (result) { //result.id  result.data result.msg
            if (result.id === 1) {
                EM.dispatchUserMsg({
                    'subject': subject,
                    'contact-email': result.data['contact-email'],
                    'inc-name': result.data['inc-name'],
                    'user': result.data['user'],
                    'msg': msg
                }, function (e, m) {
                    if (!e) {
                        // res.status(200).send('ok');
                        res.status(200).send({'id': 1});
                    } else {
                        for (k in e)
                            console.log('ERROR : ', k, e[k]);
                        // res.status(400).send('unable to dispatch password reset');
                        res.status(200).send({'id': 2});
                    }
                });
            }
        });
    });


    app.get('/reset-password', function (req, res) {
        var email = req.query["e"];
        var passH = req.query["p"];
        AM.validateResetLink(email, passH, function (e) {
            if (e != 'ok') {
                res.redirect('/');
            } else {
                // save the user's email in a session instead of sending to the client //
                req.session.reset = {email: email, passHash: passH};
                res.render('reset', {title: 'Reset Password'});
            }
        })
    });

    app.post('/reset-password', function (req, res) {
        var nPass = req.body['pass'];
        // retrieve the user's email from the session to lookup their account and reset password //
        var email = req.session.reset.email;
        // destory the session immediately after retrieving the stored email //
        req.session.destroy();
        AM.updatePassword(email, nPass, function (e, o) {
            if (o) {
                res.status(200).send('密码更新成功！');
            } else {
                res.status(400).send('密码更新失败');
            }
        })
    });

    //Guard unLogin User
    app.all('*', function (req, res, next) {
        if (req.session.user == null) {
            // if user is not logged-in redirect back to login page //
            res.redirect('/');
        } else {
            next();
        }
    });

    app.get('/home', function (req, res) {
        res.render('home', {
            title: 'Control Panel',
            udata: req.session.user
        });
    });

    //更新申请用户状态
    app.post('/account-update-status', function (req, res) {
        var userId = req.body['user_id'];
        var status = Number(req.body['status']);
        console.log(' --- id --- ' + userId);
        AM.updateAccountStatus({'id': userId, 'status': status}, function (result) {
            res.status(200).send(result);
        });
    });

    //更新用户信息
    app.post('/account-update', function (req, res) {
        console.log('--- account-update  pass ---', req.body['pass']);
        var data = {
            'id': req.session.user._id,
            // 'user': req.body['user'], //不能更新用户名
            // 'pass-tf': req.body['pass'],
            // 'inc-name': req.body['inc-name'],
            // 'inc-address': req.body['inc-address'],
            // 'inc-property': req.body['inc-property'],
            'contact-name': req.body['contact-name'],
            'contact-phone': req.body['contact-phone'],
            // 'contact-email': req.body['contact-email'], //不能更新联系邮箱
            'contact-position': req.body['contact-position']
            // 'contact-tel': req.body['contact-tel'],
            // 'inc-number': req.body['inc-number'],
            // 'inc-industry': req.body['inc-industry'],
            // 'business-license': req.body['business-license'],
            // 'organization-code': req.body['organization-code']
        };
        AM.updateAccount(data, req.body['pass'], function (result) {
            if (result['id'] == 1) {
                // res.status(400).send('error-updating-account');
                req.session.user = result['data'];
                // update the user's login cookies if they exists //
                if (req.cookies.user != undefined && req.cookies.pass != undefined) {
                    res.cookie('user', result.data.user, {maxAge: 900000});
                    res.cookie('pass', result.data.pass, {maxAge: 900000});
                }
            }
            result['data'] = null;
            res.status(200).send(result);
        });
    });


    //获取指定id获取信息
    app.post('/account-show', function (req, res) {
        var _id = String(req.body['id']);
        // // console.log(' --- id ---： ' + id + '  :   ' + typeof(id)) ;
        // // console.log(' --- id ---： ' + id) ;
        if (_id === 'undefined') {
            _id = req.session.user._id;
        }
        // console.log(' --- user ---： ' + req.session.user.user);
        // var user = req.session.user.user;

        console.log(' --- _id ---： ' + _id);
        AM.getRecords(_id, function (result) { //result.id  result.data result.msg
            res.status(200).send(result);
        });
    });


    app.get('/account-show', function (req, res) {
        res.render('showAccount');
    });


    app.post('/logout', function (req, res) {
        res.clearCookie('user');
        res.clearCookie('pass');
        req.session.destroy(function (e) {
            res.status(200).send('ok');
        });
    });

    app.post('/account-delete', function (req, res) {
        var id = req.body['id'];

        AM.deleteAccount(id, function (result) {

            if (id == req.session.user._id) {
                res.clearCookie('user');
                res.clearCookie('pass');
                req.session.destroy()
            }

            res.status(200).send(result);


        });
    });

    // add & update excels
    app.get('/excel', function (req, res) {
        var data = {};

        data.title = 'Excel Panel';
        data.udata = req.session.user;

        var callback = function (e, record) {
            var excel, excels = [];
            if (record.length != 0) {
                for (var i in record) {
                    excel = record[i].excel.replace(/\[(.*)\]/, function (match, key) {
                        return key;
                    });
                    if (excel) {
                        excels.push(excel);
                    }
                }
                data.excel = "[" + excels.join(",") + "]";
            }
            res.render('excel', data);
        };

        if (req.session.user.user == "admin") {
            EXM.getAllRecords(callback);
        } else {
            var a = [{user: req.session.user.user}, {user: "admin"}];
            EXM.getUserRecords(a, callback);
        }

    });

    app.post('/excel', function (req, res) {
        EXM.updateExcel({
            user: req.session.user.user,
            excel: req.body['excel']
        }, function (e, o) {
            if (e) {
                res.status(400).send('error-updating-excel');
            } else {
                res.status(200).send('ok');
            }
        });
    });

    app.get('/reservation', function (req, res) {
        // , req.session.user
        console.log('reservation  ');
        var roomId = req.query.roomId;
        console.log("reservation: " + roomId);
        //最开始只提供第一会议室
        if (roomId === undefined || roomId === '' || roomId !== '1') {
            res.render('404');
        } else {
            res.render('reservation', {
                title: 'Reservation Panel',
                udata: req.session.user,
                room_id: roomId
            });
        }
    });

    // app.get('/reservation-show', function (req, res) {
    //     console.log('reservation-show');
    //     var id = req.query.id;
    //     res.render('showReservation');
    // });


    //获取天气
    app.get('/weathers-get', function (req, res) {
        console.log('weathers-get');
        WRM.getWeather(function (result) { // result 是结果列表
            if (result['id' == 0]) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                // console.log("result: ", result);
                res.status(200).send(result.data);
            }
        });
    });


    //获取天气
    app.post('/weathers-store', function (req, res) {
        console.log('weathers-store');

        var weatherList = req.body['weatherList'];

        console.log("weatherList : " + weatherList);

        WRM.updateWeathers(weatherList, function (e, result) { // result 是结果列表
            if (e) { //if e不为空， 表示出错
                res.status(400).send('error-getting-reservation');
            } else { //成功
                console.log("result: ", result);
                res.status(200).send(result);
            }
        });
    });

    //查询预约详细信息
    app.get('/reservation-query', function (req, res) {
        console.log('reservation - query');
        var id = Number(req.query.id);
        REM.getOneReservation({"id": id}, function (result) { // result 是结果列表
            res.status(200).send(result);
        });
    });

    //判断当前会议室的时间段是否有预约
    app.post('/check-room-reservation', function (req, res) {
        var roomId = req.body['room_id']; //
        var start = Number(req.body['start']);
        var end = Number(req.body['end']);
        var user = req.session.user.user;
        //1-查看 2-更新 3-添加
        var type = Number(req.body['type']);
        var findQuery = {'type': type, 'user': user, 'room_id': roomId, 'start': start, 'end': end};
        // 验证用户是否是管理员
        AM.checkUserRole(user, function (result) {
            findQuery['role'] = result.id;
            REM.checkRoomReservation(findQuery, function (result) {
                res.status(200).send(result);

            });
        });

    });


    ///url: /reservation-get?room_id=1&start=1485734400&end=1489363200
    app.get('/reservation-get', function (req, res) {
        console.log('reservation ---- get');
        //获取room_id
        var roomId = req.query.roomId;
        console.log("--- roomId: ---" + roomId);

        // var query = {"room_id": roomId, 'status': {'$nin': [4,5]}};
        //加载当前会议室预约列表，已取消的
        var query = {"room_id": roomId, 'status': {'$ne': 5}};
        REM.getAllReservations(query, function (result) { // o是结果列表
            res.status(200).send(result);

        });
    });


    var status = [
        {id: 1, msg: '申请中', btnStatus: 'loading', color: '#F2AE43'},
        {id: 2, msg: '申请成功', btnStatus: 'success', color: '#58B957'},
        {id: 3, msg: '申请失败', btnStatus: 'failed', color: '#DB524B'},
        {id: 4, msg: '已结束', btnStatus: 'finished', color: '#333333'},
        {id: 5, msg: '已取消', btnStatus: 'canceled', color: '#6A2C70'} //用户申请成功后删除
    ];

    //预约列表
    function reservationToTidy(data, items) {
        items = items || ['id', 'user_id', 'inc_name', 'contact_phone', 'room_id', 'title', 'start', 'end', 'status', 'date'];
        var tidy = [];

        var now = moment();
        data.forEach(function (element, index) {
            tidy[index] = {};
            items.forEach(function (item) {
                tidy[index][item] = element[item];

                if (item == 'status') {
                    var end = moment.unix(element['end']);
                    //使每个预约以不同的颜色显示， 1， 2， 3 , 4, 5
                    if (now > end) { //如果已经结束，更新预约状态
                        if (element['status'] !== 4) { //如果该预约还没有置为已结束状态
                            REM.updateReservationStatus({'id': element['id'], 'status': 4}, null);
                        }
                        tidy[index]['color'] = status[3].color;
                        tidy[index]['msg'] = status[3].msg;
                        tidy[index]['status'] = status[3].btnStatus;
                    } else {
                        tidy[index]['color'] = status[Number(element[item]) - 1].color;
                        tidy[index]['msg'] = status[Number(element[item]) - 1].msg;
                        tidy[index]['status'] = status[Number(element[item]) - 1].btnStatus;
                    }
                }
                moment.locale("zh-cn");
                if (item == 'start') {
                    var start = moment.unix(tidy[index]['start']);
                    tidy[index]['start'] = start.format("LLL");
                }

                if (item == 'end') {
                    var end = moment.unix(tidy[index]['end']);
                    tidy[index]['end'] = end.format("LLL");
                }

                if (item == 'date') {
                    tidy[index]['startEnd'] = tidy[index]['start'] + " - " + tidy[index]['end'];
                }
            })
        });
        return tidy;
    }

    //用户账号列表
    function accountToTidy(data) {
        console.log('accountToTidy[0] --- ' + data[0]);
        var items = ['_id', 'user', 'status', 'inc-name', 'contact-name', 'contact-phone', 'contact-email', 'date'];
        var tidy = [];

        var now = moment();
        data.forEach(function (element, index) {
            tidy[index] = {};
            items.forEach(function (item) {
                tidy[index][item] = element[item];

                if (item == 'status') {
                    //1， 2， 3
                    tidy[index]['color'] = status[Number(element[item]) - 1].color;
                    tidy[index]['msg'] = status[Number(element[item]) - 1].msg;
                    tidy[index]['status'] = status[Number(element[item]) - 1].btnStatus;
                }
                moment.locale("zh-cn");
                if (item == 'date') {
                    var start = moment.unix(tidy[index]['date']);
                    // var start = moment(tidy[index]['date']);
                    tidy[index]['date'] = '<b>申请时间</b>:&emsp;' + start.format("LLL");
                }

                if (item == '_id') {
                    tidy[index]['id'] = element[item];
                }
                if (item == 'user') {
                    // tidy[index]['user'] = "<b>用户名:</b> " + element[item] + "&emsp;<b>联系手机:</b> " +
                    //     element['contact-phone'] + "&emsp;<b>联系邮箱:</b> " + element['contact-email'];
                    tidy[index]['user'] = "用户名:  " + element[item] + "&emsp;联系手机:  " +
                        element['contact-phone'] + "&emsp;联系邮箱:  " + element['contact-email'];
                }
                if (item == 'inc-name') {
                    tidy[index]['inc'] = "公司/团队名称:  " + element[item];
                }
            })
        });
        return tidy;
    }

    //返回我的预约列表页面，
    app.get('/reservation-my', function (req, res) {
        console.log('reservation-my');
        var user = req.session.user.user;
        var query = {"user": user, 'status': {'$ne': 5}}; //我的预约列表中不可以看见已取消的预约，只有预约管理页面才能看见
        REM.getAllReservations(query, function (result2) { // o是结果列表
            if (result2.id === 2) { //if e不为空， 表示出错
                res.render('404');
            } else { //成功
                var list = reservationToTidy(result2.data);
                res.render('myReservation', {
                    list: list
                });
            }
        });
    });


    //返回预约管理列表页面
    app.get('/reservation-manage', function (req, res) {
        console.log('reservation-manage');
        var user = req.session.user.user;

        // 验证用户是否是管理员
        AM.checkUserRole(user, function (result1) {
            if (result1.id === 1) { //管理员
                REM.getAllReservations({}, function (result2) { // o是结果列表
                    if (result2.id === 2) { //if e不为空， 表示出错
                        res.render('404');
                    } else {
                        var list = reservationToTidy(result2.data);
                        res.render('manageReservation', {
                            list: list
                        });
                    }
                });
            } else { //普通用户和特殊用户
                res.render('404');
            }
        });
    });


    //用户角色检查
    app.post('/account-check', function (req, res) {
        console.log('account-check');
        var user = req.session.user.user;
        AM.checkUserRole(user, function (result) {
            console.log('account-check  result ----- ' + result);
            res.status(200).send(result);
        });

    });

    //用户管理列表, 判断是否是管理员
    app.get('/account-manage', function (req, res) {
        var user = req.session.user.user;
        AM.checkUserRole(user, function (result1) {
            if (result1.id === 1) { //管理员
                AM.getAllRecords({'role': 2}, function (result) { // o是结果列表
                    console.log('result --- ' + result);
                    if (result.id == 2) { //if id ==2 表示出错
                        res.render('404');
                    } else { //成功
                        var data = result.data;
                        var accountList = [];
                        if (data)
                            accountList = accountToTidy(data);
                        res.render('manageAccount', {
                            accountList: accountList
                        });
                    }
                });
            }
            else { //如果不是管理员(普通用户或者特殊用户）
                res.render('404');
            }
        });


    });


    //更新预约状态 ， 1 - 申请中 2 - 申请从成功 3 - 申请失败  4 - 已完成 5-已取消
    app.post('/reservation-update-status', function (req, res) {
        console.log('reservation-update-status');

        var reservationId = Number(req.body['reservation_id']);
        var user = req.session.user.user;
        var status = Number(req.body['status']);

        console.log(' --- status --- ' + status);

        var retrunValue = {};
        //检查用户是否为管理员
        AM.checkUserRole(user, function (result) {
            if (result.id === 1) { //检查成功， 更新状态
                REM.updateReservationStatus({'id': reservationId, 'status': status}, function (result) {
                    if (result.id == 1) {
                        retrunValue['id'] = 1;
                        retrunValue['msg'] = '修改成功';
                    } else {
                        retrunValue['id'] = 2;
                        retrunValue['msg'] = '修改失败';
                    }
                    //返回结果
                    res.status(200).send(retrunValue);
                });
            } else { //普通用户或者特殊用户
                retrunValue['id'] = 2;
                retrunValue['msg'] = '没有修改权限';
                //返回结果
                res.status(200).send(retrunValue);
            }

        });
    });


    //返回申请预约页面
    app.get('/reservation-add', function (req, res) {
        console.log('get reservation-add');
        var roomId = req.query.roomId;
        console.log("roomId ---- : " + roomId);
        res.render('addReservation', {
            title: roomId
        });
    });

    //添加预约申请
    app.post('/reservation-add', function (req, res) {
        console.log('post reservation-add');
        //1-查看 2-更新 3-添加
        var type = Number(req.body['type']);

        //如果是添加才设置这两项
        if (type === 3) {
            var incName = req.body['inc_name']; //公司/团队名称
            var contactTel = req.body['contact_tel']; //公司电话
        }

        var title = req.body['title'];
        var contactName = req.body['contact_name']; //联系人姓名
        var roomName = req.body['room_name'];
        var contactPhone = req.body['contact_phone'];
        var contactEmail = req.body['contact_email'];
        var contactPosition = req.body['contact_position']; //联系人职位

        var startTime = req.body['start'];
        var endTime = req.body['end'];
        var allDay = req.body['allDay'];

        var postName = req.body['post_name'];
        var recruitProfessional = req.body['recruit_professional'];
        var enrolmentNumbers = req.body['enrolment_numbers'];
        var workingPlace = req.body['working_place'];
        var jobRequirements = req.body['job_requirements'];
        var workingConditions = req.body['working_conditions'];

        var theIntern = req.body['the_intern'];
        var detailInfo = req.body['detail_info'];

        var id = Number(req.body['id']);

        var roomId = req.body['room_id'];

        //申请提交时间
        var date = moment().unix();

        var user = req.session.user.user;
        var userId = req.session.user._id;

        var start = Number(startTime);
        var end = Number(endTime);

        if (Number(allDay) == 1) {
            allDay = true;
        } else {
            allDay = false;
        }

        //标记状态为申请中, 如果是管理员申请或者是特殊用户，直接设置为申请通过
        var status = 1; //默认标记为申请中

        //检查用户是否为管理员或者特殊用户
        AM.checkUserRole(user, function (result) {
            var mStart = moment.unix(start);
            var mEnd = moment.unix(end);
            console.log(' --- checkUserRole --- ', result.id);
            if (result.id === 2) { //普通用户
                //普通用户只能申请上班时间
                if (mStart.weekday() > 5 || mEnd.weekday > 5 || mStart.hours() > 18) {
                    res.status(200).send({
                        'id': 2,
                        'msg': '只能申请上班时间段（每天8点-18点）, 如有问题请联系管理员'
                    });
                }

                if (mEnd.hours() > 18 || (mEnd.hours() == 18 && mEnd.minutes() > 0)) {
                    res.status(200).send({
                        'id': 2,
                        'msg': '只能申请上班时间段（每天8点-18点）, 如有问题请联系管理员'
                    });
                }
                status = 1; //申请中
            } else {  //管理员或者特殊用户
                status = 2; //申请通过
            }
            var data = {
                user: user,
                'user_id': userId,
                'id': id,
                'room_id': roomId,
                'title': title,

                'contact_name': contactName,
                'room_name': roomName,
                'contact_phone': contactPhone,
                'contact_email': contactEmail,
                'contact_position': contactPosition,

                'start': start,
                'end': end,
                'allDay': allDay,

                'post_name': postName,
                'recruit_professional': recruitProfessional,
                'enrolment_numbers': enrolmentNumbers,
                'working_place': workingPlace,
                'job_requirements': jobRequirements,
                'working_conditions': workingConditions,
                'the_intern': theIntern,
                'detail_info': detailInfo,

                'status': status,
                'date': date

            };

            if (type === 3) { //如果是添加预约
                data['inc_name'] = incName;
                data['contact_tel'] = contactTel;
            }

            //保存到数据库中
            REM.updateReservation(data, type, function (result) {
                console.log('result : ' + result);
                res.status(200).send(result);
            });
        });


    });


    //删除预约，如果是普通用户删除预约分两种情况： 1. 还没有申请成功，可以直接删除； 2.如果申请成功，则记录为已取消
    app.post('/reservation-delete', function (req, res) {
        console.log('reservation-delete');
        var data = {};
        data['id'] = req.body['id'] ? Number(req.body['id']) : null;
        var type = Number(req.body['type']); //1 - 删除， 2 - 设为已取消状态
        var user = req.session.user.user;

        AM.checkUserRole(user, function (result) {
            console.log('user ------ ' + result.id);
            if (result.id === 1 || result.id === 3) { //用户为管理员或者特殊用户
                REM.deleteReservation(data, function (values) {
                    console.log('delete values ' + values);
                    res.status(200).send(values);
                });
            } else if (result.id === 2) {//普通用户, 先检查该预约是否是该用户的
                REM.getOneReservation({'user': user, 'id': data['id']}, function (result2) {
                    if (result2.id === 1) { //是该用户的
                        console.log(' delete type ---- ', type);
                        if (type === 2) { //要设置为已取消状态
                            var status = result2.data['status'];
                            if (status === 2) { //如果已经预约成功
                                //标记status为已取消
                                status = 5;
                                REM.updateReservationStatus({'id': data['id'], 'status': status}, function (result3) {
                                    if (result3.id === 1) {
                                        res.status(200).send({'id': 1, 'msg': '取消成功'});
                                    } else {
                                        res.status(200).send({'id': 2, 'msg': '取消失败'});
                                    }
                                })
                            } else { //如果没有预约成功，直接删除
                                REM.deleteReservation(data, function (values) {
                                    console.log('delete values ' + values);
                                    res.status(200).send(values);
                                });
                            }
                        } else {//如果是要删除
                            REM.deleteReservation(data, function (values) {
                                console.log('delete values ' + values);
                                res.status(200).send(values);
                            });
                        }
                    } else { //删除
                        res.status(200).send({'id': 2, 'msg': '删除失败'});
                    }
                });

            }
        });

    });


    app.get('/information', function (req, res) {
        res.render('information', {
            title: 'information Panel',
            udata: req.session.user
        });
    });

    app.get('/information-get', function (req, res) {
        var callback = function (e, record) {
            var infos = [], result;

            if (record && record.length != 0) {
                for (var i in record) {
                    infos.push(JSON.parse(record[i].taskItem));
                }
            }
            result = infos.length === 0 ? undefined : JSON.stringify(infos);
            if (e) {
                res.status(400).send('error-getting-information');
            } else {
                res.status(200).send(result);
            }
        };

        if (req.session.user.user == "admin") {
            IFM.getAllRecords(callback);
        } else {
            IFM.getInformation({
                user: req.session.user.user,
            }, callback);
        }
    });

    app.post('/information-add', function (req, res) {
        IFM.proxyInformation({content: req.body['content'], taskItem: req.body['taskItem']}).then((success) => {
            if (success) {
                res.status(200).send('ok');
            } else {
                res.status(400).send('error-adding-reservation');
    }
    }).
        catch((err) => {
            res.status(400).send('error-adding-reservation');
    })
        ;

    });

    app.post('/file-get', function (req, res) {
        FIM.getFile({index: req.body['index']}, function (e, o) {
            if (e) {
                res.status(400).send('error-getting-reservation');
            } else {
                res.status(200).send(o);
            }
        });
    });

    //Guard Normal User
    app.all('*', function (req, res, next) {
        if (req.session.user && req.session.user.user == "admin") {
            next();
        } else {
            res.render('404', {title: 'Page Not Found'});
        }
    });

    app.get('/printAccount', function (req, res) {
        AM.getAllRecords(function (e, accounts) {
            res.render('print', {title: 'Account List', accts: accounts});
        })
    });

    // app.get('/resetAccount', function (req, res) {
    //     AM.delAllRecords(function () {
    //         res.redirect('/print');
    //     });
    // });

    app.get('/printExcel', function (req, res) {
        EXM.getAllRecords(function (e, excels) {
            res.render('printExcel', {title: 'Excel List', exls: excels});
        });
    });

    // app.get('/resetExcel', function (req, res) {
    //     EXM.delAllRecords(function () {
    //         res.redirect('/printExcel');
    //     });
    // });

    app.get('/printReservation', function (req, res) {
        REM.getAllReservations(function (e, reservations) {
            res.render('printReservation', {title: 'Reservations List', resns: reservations});
        });
    });

    // app.get('/resetReservation', function (req, res) {
    //     REM.delAllRecords(function () {
    //         res.redirect('/printReservation');
    //     });
    // });

    app.get('/printFile', function (req, res) {
        FIM.getAllRecords(function (e, files) {
            res.render('printFile', {title: 'files List', files: files});
        });
    });

    // app.get('/resetFile', function (req, res) {
    //     FIM.delAllRecords(function () {
    //         res.redirect('/printFile');
    //     });
    // });

    app.all('*', function (req, res) {
        res.render('404', {title: 'Page Not Found'});
    });

};